package io.renren.security.controller;

import io.renren.common.exception.RRException;
import io.renren.common.pojo.R;
import io.renren.modules.common.BaseController;
import io.renren.security.pojo.AccessToken;
import io.renren.security.pojo.SecurityUser;
import io.renren.security.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/auth")
@Api(description = "登陆授权接口")
public class AuthController extends BaseController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * @param username 用户名
     * @param password 密码
     * @return AccessToken
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public R<AccessToken> login(@ApiParam("用户名") @RequestParam String username,
                                @ApiParam("密码") @RequestParam String password,
                                @ApiParam(hidden = true) HttpServletRequest request) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);
        authRequest.setDetails(new WebAuthenticationDetails(request));

        try{
            Authentication authentication = authenticationManager.authenticate(authRequest);
            SecurityUser user = (SecurityUser) authentication.getPrincipal();

            AccessToken accessToken = jwtUtils.generateToken(user.getUsername());
            return R.ok(accessToken);
        }catch (Exception e){
            throw new RRException("用户名/密码不正确",HttpStatus.SC_UNAUTHORIZED);
        }
    }

    @ApiOperation("通过老Token换取新Token")
    @RequestMapping(value = "/refresh",method = RequestMethod.POST)
    public R<AccessToken> refresh(@ApiParam("老Token") @RequestParam String token){
        String username = jwtUtils.getUsernameByToken(token);
        AccessToken accessToken = jwtUtils.generateToken(username);
        return R.ok(accessToken);
    }
}
